package com.fred

import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.*
import com.fred.bean.KeyStoreJson
import com.fred.bean.getKeyStores
import com.fred.bean.saveKeyStores
import com.fred.util.ColorUtil
import com.fred.util.PropertiesUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


private lateinit var keyStores: SnapshotStateList<KeyStoreJson>
private lateinit var selectedIndex:MutableState<Int>
@Composable
fun keyStoreManager(isShow: MutableState<Boolean>) {
    if (isShow.value) {
        Dialog(
            onCloseRequest = {
                isShow.value = false
            },
            resizable = false,
            icon = painterResource("ic_sign.svg"),
            title = "签名管理",
            state = DialogState(
                position = getPosition(700f, 432.6f),
                size = DpSize(700.dp, 432.6.dp)
            )
        ) {
            keyStores = remember { mutableStateListOf() }
            selectedIndex = remember { mutableStateOf(-1) }
            Column(
                modifier = Modifier.fillMaxWidth()
                    .fillMaxHeight(),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {

                Row(modifier = Modifier.padding(16.dp, 0.dp).fillMaxWidth().height(32.dp)) {
                    //FIXME 添加删除确认对话框
//                    val deleteConfirm = remember { mutableStateOf(false) }
                    TextButton(modifier = Modifier.padding(0.dp), onClick = {
                        coroutineScope.launch(Dispatchers.IO) {
                            var temp:KeyStoreJson? = null
                            val save = arrayListOf<KeyStoreJson>()
                            keyStores.forEachIndexed { _, keyStoreJson ->
                                if (keyStoreJson.isDefault) {
                                    temp = keyStoreJson
                                } else {
                                    save.add(keyStoreJson)
                                }
                            }
                            val t = temp
                            if (t != null) {
                                selectedIndex.value = -1
                                keyStores.remove(t)
                                saveKeyStores(save)
                            }
                        }
                    }) {
                        Image(
                            painter = painterResource("ic_delete.svg"),
                            contentDescription = "delete icon"
                        )
                        Text("删除选中", color = ColorUtil.mainFont, fontSize = 12.sp)
                    }
                    val addKeyStore = remember { mutableStateOf(false) }
                    TextButton(modifier = Modifier.padding(0.dp), onClick = {
                        addKeyStore.value = true
                    }) {
                        Image(
                            painter = painterResource("ic_add.svg"),
                            contentDescription = "add icon"
                        )
                        Text("添  加", color = ColorUtil.mainFont, fontSize = 12.sp)
                    }
                    addKeyStore(addKeyStore, onAdded = {
                        if (keyStores.size == 0){
                            it.isDefault = true
                            selectedIndex.value = 0
                        }
                        keyStores.add(it)
                        coroutineScope.launch(Dispatchers.IO) {
                            val save = arrayListOf<KeyStoreJson>()
                            keyStores.forEach { ksj ->
                                save.add(ksj)
                            }
                            saveKeyStores(save)
                        }
                    })
                }
                table()
            }
            coroutineScope.launch(Dispatchers.IO) {
                val kss = getKeyStores()
                if (kss.isNotEmpty()) {
                    keyStores.clear()
                    keyStores.addAll(kss)
                    for ((index, ksj) in keyStores.withIndex()) {
                        if (ksj.isDefault) {
                            selectedIndex.value = index
                            break
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun table() {
    Column(
        modifier = Modifier.fillMaxWidth().height(340.dp).padding(16.dp, 0.dp)
            .border(width = 1.dp, color = ColorUtil.background)
    ) {
        Row(modifier = Modifier.fillMaxWidth().background(ColorUtil.background).padding(0.dp, 8.dp)) {
            Text("keystore文件路径", modifier = Modifier.weight(2f), textAlign = TextAlign.Center)
            Text("别名", modifier = Modifier.weight(1f), textAlign = TextAlign.Center)
            Text("默认", modifier = Modifier.weight(1f), textAlign = TextAlign.Center)
        }

        LazyColumn(modifier = Modifier.fillMaxWidth()) {
            items(keyStores.size) {
                Row(modifier = Modifier.padding(0.dp, 0.dp).clickable(true, onClick = {}), verticalAlignment = Alignment.CenterVertically) {
                    Text(
                        keyStores[it].keyStorePath,
                        modifier = Modifier.weight(2f).padding(8.dp),
                        textAlign = TextAlign.Start,
                        overflow = TextOverflow.Ellipsis,
                        maxLines = 2,
                        fontSize = 12.sp
                    )
                    Text(text = keyStores[it].alias, modifier = Modifier.weight(1f), textAlign = TextAlign.Center)
//                    val checked = remember { mutableStateOf(false) }
//                    Checkbox(checked.value, modifier = Modifier.weight(1f).height(28.dp), onCheckedChange = {
//                        checked.value = it
//                    })

                    RadioButton(selected = selectedIndex.value == it, modifier = Modifier.weight(1f),onClick = {
                        if (selectedIndex.value != it) {
                            selectedIndex.value = it
                            val save = arrayListOf<KeyStoreJson>()
                            keyStores.forEachIndexed { index, keyStoreJson ->
                                keyStoreJson.isDefault = index == it
                                save.add(keyStoreJson)
                            }
                            coroutineScope.launch(Dispatchers.IO) {
                                saveKeyStores(save)
                            }
                        }
                    })
                }
                line()
            }
        }
    }
}

@Composable
fun line() {
    Box(modifier = Modifier.fillMaxWidth().height(0.5.dp).background(ColorUtil.border))
}